package com.fenghuajueli.libbasecoreui.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.fenghuajueli.libbasecoreui.constants.EventBusConstants
import com.fenghuajueli.libbasecoreui.data.entity.eventbus.EventEntity
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils
import com.fenghuajueli.libbasecoreui.viewmodel.data.LoadingData
import com.fenghuajueli.libbasecoreui.viewmodel.data.OtherCodeData
import com.fenghuajueli.libbasecoreui.viewmodel.data.ToastData
import com.fenghuajueli.module_route.UserModuleRoute
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import org.greenrobot.eventbus.EventBus
import java.util.concurrent.TimeUnit

open class BaseViewModel2 : ViewModel(), CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.IO) {

    /**
     * 显示等待对话框的数据类
     */
    @JvmField
    val loadingViewData = MutableLiveData<LoadingData>()

    /**
     * 处理其他状态的一些情况
     */
    @JvmField
    val otherStatusData = MutableLiveData<OtherCodeData>()

    @JvmField
    val finishActivityData = MutableLiveData<Int>()

    /**
     * 倒计时可用数据观察者
     */
    @JvmField
    var countDownTime = MutableLiveData<Int>()

    /**
     * 开始计时 不是倒计时的类型
     */
    @JvmField
    var timeData = MutableLiveData<Long>()

    /**
     * 等待对话框的默认数据配置类
     */
    protected var loadingData = LoadingData(LoadingData.LOADING_STOP)

    protected var toastData = ToastData("")

    @JvmField
    var permissionCheckData = MutableLiveData<Boolean>()


    /**
     * 显示loading对话框
     */
    protected fun showLoading() {
        loadingData.status = LoadingData.LOADING_START
        loadingViewData.postValue(loadingData)
    }

    protected fun showLoading(tips: String?) {
        loadingData.status = LoadingData.LOADING_START
        loadingData.loadingTips = tips
        loadingViewData.postValue(loadingData)
    }

    /**
     * 隐藏loading对话框
     */
    protected fun hideLoading() {
        loadingData.status = LoadingData.LOADING_STOP
        loadingViewData.postValue(loadingData)
    }

    protected fun showToast(content: String?) {
        ToastUtils.showShort(content)
    }


    protected fun finishActivity() {
        finishActivityData.postValue(0)
    }


    /**
     * 处理token失败
     */
    protected fun handlerTokenError() {
        hideLoading()
        UserInfoUtils.getInstance().clearLoginInfo()
        EventBus.getDefault().post(
            EventEntity(
                EventBusConstants.LOGIN_OUT,
                null
            )
        )
        ARouter.getInstance().build(UserModuleRoute.USER_LOGIN).navigation()
        finishActivity()
    }

    private var downTimeDisposable: Disposable? = null

    private var timeDisposable: Disposable? = null


    fun cancelDownTime() {
        downTimeDisposable?.dispose()
    }

    /**
     * 开始倒计时
     */
    fun startCountDownTime(count: Int) {
        cancelDownTime()
        Observable.intervalRange(0, count.toLong(), 0, 1, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<Long?> {
                override fun onSubscribe(d: Disposable) {
                    downTimeDisposable = d
                }

                override fun onError(e: Throwable) {}
                override fun onComplete() {}
                override fun onNext(t: Long) {
                    countDownTime.postValue((count - t.toInt()) * 1000)
                }
            })
    }

    /**
     * 取消计时任务
     */
    fun cancelTime() {
        timeDisposable?.dispose()
    }

    /**
     * 开始计时  不是倒计时，返回数字的单位为毫秒
     */
    fun startTime() {
        var count = 0L
        cancelTime()
        Observable.interval(0, 1000, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<Long?> {
                override fun onSubscribe(d: Disposable) {
                    timeDisposable = d
                }

                override fun onError(e: Throwable) {}
                override fun onComplete() {}
                override fun onNext(t: Long) {
                    timeData.postValue(count * 1000)
                    count++
                }
            })
    }
}